package com.vodone.v1pin.component.productlist
{
	import caurina.transitions.Tweener;
	
	import com.vodone.v1pin.component.productlist.events.GetDataEvent;
	import com.vodone.v1pin.component.productlist.renderer.ProductItemRenderer;
	import com.vodone.v1pin.core.model.MainModelLocator;
	import com.vodone.v1pin.detail.events.SendDataEvent;
	import com.vodone.v1pin.productlist.vo.ProductItemVO;
	
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.ui.Keyboard;
	import flash.ui.Mouse;
	import flash.ui.MouseCursor;
	import flash.utils.Dictionary;
	import flash.utils.getTimer;
	
	import mx.controls.Spacer;
	import mx.core.Container;
	import mx.core.UIComponent;
	import mx.core.mx_internal;
	import mx.events.ResizeEvent;
	import mx.events.ScrollEvent;
	
	[Event(name="getDataEvent",type="com.vodone.v1pin.component.productlist.events.GetDataEvent")]
	[Event(name="sendDataEvent",type="com.vodone.v1pin.detail.events.SendDataEvent")]
	public class MyProductList extends Container
	{
		public function MyProductList()
		{
			super();
			this.setStyle( "backgroundColor" , 0xffffff );
			this.setStyle("verticalScrollBarStyleName","myScroll2");
			this.horizontalScrollPolicy = "off";
			addEventListener( Event.ADDED_TO_STAGE  ,addStageHandler );
		}
		/**
		 * 数据源 改变后调用
		 */		
		public function clear():void
		{
			for( var p:String in currentShowPageDict )
			{
				removePage( int(p) );
			}
			overCount = 0;
			pageDict = new Dictionary();
			currentShowPageDict = new Dictionary();
			positionDict = new Dictionary();
			overDict = new Dictionary();
			removeLayoutItem();
			this.verticalScrollPosition = 0;
			pageHaveRequestList= [];
//			rowLabel.visible = false;
		}
		
		private var cacheDirty:Boolean = false;
		private function invalidateCache():void
		{
			cacheDirty = true;
			invalidateProperties();
		}
		/**
		 * 设置某一页的数据
		 *  
		 * @param page 页码
		 * @param data 数据列表
		 */		
		public function setData( page:int , data:Array ):void
		{
			pageDict[ page ] = data;
			invalidateCurrentContent();
		}
		private function addStageHandler( e:Event ):void
		{
			verticalScrollPosition = 0;
			addEventListener( ScrollEvent.SCROLL , scrollHandler );
			addEventListener( Event.REMOVED_FROM_STAGE , removeStageHandler );
			addEventListener( ResizeEvent.RESIZE , resizeHandler );
			addEventListener( MouseEvent.MOUSE_WHEEL , mouseWheelHandler );
			addEventListener( MouseEvent.MOUSE_DOWN , mouseDownHandler  );
			addEventListener( MouseEvent.MOUSE_MOVE, mouseMoveHandler , true );
			addEventListener( MouseEvent.MOUSE_UP , mouseUpHandler );
			addEventListener( MouseEvent.ROLL_OUT , rollOutHandler );
			systemManager.addEventListener(MouseEvent.MOUSE_WHEEL, systemWheelHandler );
			addEventListener( MouseEvent.CLICK , mouseClickHandler , true );
			stage.addEventListener( KeyboardEvent.KEY_DOWN , mykeydownHandler );
		}
		private function removeStageHandler( e:Event ):void
		{
			removeEventListener( ScrollEvent.SCROLL , scrollHandler );
			removeEventListener( Event.REMOVED_FROM_STAGE , removeStageHandler );
			removeEventListener( ResizeEvent.RESIZE , resizeHandler );
			removeEventListener( MouseEvent.MOUSE_WHEEL , mouseWheelHandler );
			removeEventListener( MouseEvent.MOUSE_DOWN , mouseDownHandler  );
			removeEventListener( MouseEvent.MOUSE_MOVE, mouseMoveHandler , true );
			removeEventListener( MouseEvent.MOUSE_UP , mouseUpHandler , true );
			removeEventListener( MouseEvent.ROLL_OUT , rollOutHandler );
			removeEventListener( MouseEvent.CLICK , mouseClickHandler , true );
			stage.removeEventListener( KeyboardEvent.KEY_DOWN , mykeydownHandler );
		}
		
		private var mouseIsDown:Boolean = false;
		private var mouseDownY:Number;
		private var mosueIsMove:Boolean = false;
		private function systemWheelHandler(e:Event):void
		{
			e.preventDefault();
		}
		private function mouseDownHandler(e:MouseEvent):void
		{
			mouseIsDown = true;
			mouseDownY = e.stageY;
		}
		private function mouseUpHandler(e:MouseEvent):void
		{
			mouseIsDown = false;
			fixScrollPos();
			Mouse.cursor = MouseCursor.AUTO;
		}
		private function mouseMoveHandler( e:MouseEvent ):void
		{
			if( mouseIsDown )
			{
				mosueIsMove = true;
				Mouse.cursor = MouseCursor.HAND;
				var mouseY:Number = e.stageY;
				var p:Number = verticalScrollPosition - ( mouseY - mouseDownY ); 
//				trace("mouseDownY:" + mouseDownY + ",mouseY:" + mouseY + ",verticalScrollPosition:" + verticalScrollPosition + ",p:" + p);
				this.verticalScrollPosition = p;
				layoutRowLabel( p );
				mouseDownY = mouseY;
			}
		}
		private function rollOutHandler(e:MouseEvent):void
		{
			mouseIsDown = false;
			Mouse.cursor = MouseCursor.AUTO;
			fixScrollPos();
		}
		
		private function mouseClickHandler( e:MouseEvent ):void
		{
			if( mosueIsMove )
			{
				e.stopImmediatePropagation();
				mosueIsMove = false;
			}
		}
		
		private function mouseWheelHandler(e:MouseEvent):void
		{
			e.stopImmediatePropagation();
			e.preventDefault();
			if( isExeWheelingEffect ) return;
			if( this.verticalScrollPosition + this.height + 300  >= this.maxPosition && e.delta < 0 ) 
			{
				return;
			}
			isExeWheelingEffect = true;
//			trace("鼠标滑轮滚动前位置：" + this.verticalScrollPosition );
			var wheelHeight:Number = Math.ceil( ( rowHeight + verticalGap ) );
			if( e.delta < 0 )// 向下滚动
			{
				var p:Number = Math.min( verticalScrollPosition + wheelHeight , maxPosition );
//				trace("鼠标滑轮，向下滚动：" + p );
				gotoPosition( p , mouseWheelEndHandler );
			}
			else// 向上顿东
			{
				var p2:Number = Math.max( verticalScrollPosition - wheelHeight , 0 );
//				trace("鼠标滑轮，向上滚动：" + p2 );
				gotoPosition( p2, mouseWheelEndHandler );
			}
		}
		private var isExeWheelingEffect:Boolean = false;
		private function mouseWheelEndHandler():void
		{
			fixScrollPos();
			isExeWheelingEffect = false;
//			rowLabel.visible = true;
			invalidateCurrentContent();
			if( this.verticalScrollBar && this.verticalScrollPosition <= 5 ){
				MainModelLocator.getInstance().navExtends = true;
			}else if(this.verticalScrollBar && this.verticalScrollPosition > 5){
				MainModelLocator.getInstance().navExtends = false;
			}
//			trace( "滚动完成滚动条位置：" + this.verticalScrollPosition + "time:" + getTimer() );
		}
		
		public var enableKeyboard:Boolean = true;
		private function mykeydownHandler(e:KeyboardEvent):void
		{
			if( !enableKeyboard ) return;
			var pos:Number = verticalScrollPosition;
			switch(e.keyCode)
			{
				case Keyboard.DOWN:
					pos = pos + rowHeight + verticalGap;
					pos = pos > maxPosition - height ? maxPosition - height : pos;
					//					verticalScrollPosition = pos;
					gotoPosition( pos );
					//					trace("nextRow:" + pos);
					break;
				case Keyboard.UP:
					pos = pos - rowHeight - verticalGap;
					pos = pos < 0 ? 0 : pos;
					//					verticalScrollPosition = pos;
					gotoPosition( pos );
					//					trace("preRow:" + pos );
					break;
			}
		}
		
		private function resizeHandler( e:ResizeEvent ):void
		{
			if( width != e.oldWidth )
			{
				//				trace("resize:: width:" + this.width + "oldWidth::" + e.oldWidth + ";; time::" + getTimer() )
				for ( var p:String in currentShowPageDict )
				{
					removePage( int(p) );
				}
				positionDict = new Dictionary();
				for( var key:Object in outItemPositionDict )
				{
					positionDict[ key ] = outItemPositionDict[key];
				}
				overDict = new Dictionary();
				verticalScrollPosition = 0;
				invalidateCurrentContent();
				invalidateCache();
			}
		}
		
		
		private function scrollHandler( e:ScrollEvent = null ):void
		{
			if( e && ( e.delta < 0 && e.position < 0 ) )
			{
				e.preventDefault();
				trace("e.delta::" + e.delta );
				if( Math.abs( e.delta ) == 15 )
				{
					this.verticalScrollPosition -= e.delta;
				}
				fixScrollPos( 0.01 );
				return;
			}
			//			trace(e.delta + "---" + e.detail + "---" + e.position );
			invalidateCurrentContent();
			
			if( this.verticalScrollBar && this.verticalScrollPosition <= 5 ){
				MainModelLocator.getInstance().navExtends = true;
			}else if(this.verticalScrollBar && this.verticalScrollPosition > 5){
				MainModelLocator.getInstance().navExtends = false;
			}
		}
		
		// 修正滚动条位置
		private function fixScrollPos( t:Number = .5 ):void
		{
			var overPosition:Number = rowHeight + verticalGap - verticalScrollPosition % ( rowHeight + verticalGap );
			trace("overPosition::" + overPosition );
			if( overPosition > 0 && overPosition != ( rowHeight + verticalGap ) )
			{
				if( overPosition > ( rowHeight + verticalGap ) / 2 )
				{
					var p2:Number = Math.max( verticalScrollPosition + overPosition - ( rowHeight + verticalGap )  , 0 );
					gotoPosition( p2 , null , t );
				}
				else
				{
					var p:Number = Math.min( verticalScrollPosition + overPosition , maxPosition );
					gotoPosition( p , null , t );
				}
				
			}
		}
		
		public function gotoPosition( p:Number , callback:Function = null , t:Number = 0.5 ):void
		{
			if( callback == null ) callback = mouseWheelEndHandler;
			layoutRowLabel( p , t );
//			rowLabel.visible = false;
			Tweener.addTween( this,{verticalScrollPosition:p,time:t,transition:"easeOutQuint",onComplete:callback} );
		}
		
		public function set recommendCount( count:int ):void
		{
			overCount = count * 3;
			invalidateCurrentContent();
		}
		
		/**
		 * 根据当前滚动条的位置来设置显示列表
		 */		
		private function commitCurrentContent():void
		{
			var start:Number = getTimer();
			// 计算页数
			pageCount = Math.ceil( ( totalCount + overCount) / pageSize );
			// 删除屏幕区域外部的item
			var pages:Array = getNeedShowPages( verticalScrollPosition );
			for( var page:Object in currentShowPageDict )
			{
				if( pages.indexOf( page ) < 0 )
				{
					removePage( int( page ) );
				}
			}
			// 查看屏幕显示区域，如果没有，则请求
			for each( var p:int in pages )
			{
				if( p < 0 ) continue;
				//				trace("showPage::" + p );
				// 有缓存而
				if( pageDict[ p ] != null  )
				{
					// 没有在显示
					if( currentShowPageDict[ p ] == null )
					{
						showPage( p );
//						trace("showPage in local::" + p );
					}
				}
				else // 没有缓存
				{
					if( pageHaveRequestList.indexOf( p ) < 0 )	
					{
						dispatchEvent( new GetDataEvent( p , pageSize ) );	
//						trace("showPage in remote::" + p );
					}
					
				}
			}
			var end:Number = getTimer();
			//			trace( "更新显示列表使用时间：：" + ( end - start ) + " ms" );
		}
		/**
		 * 根据滚动位置得到行数 
		 */		
		private function getRowIndexByPosition( position:int ):int
		{
			var index:int = Math.floor( ( position ) / ( rowHeight + verticalGap ) ); 
			return index;
		}
		/**
		 * 根据行得到页码
		 */		
		private function getPageByRowIndex( rowIndex:int ):int
		{
			return Math.floor( rowIndex / ROW_COUNT_PERPAGE );
		}
		/**
		 * 返回一个数据组， 数组元素为int型页码
		 */		
		private function getNeedShowPages( position:int ):Array
		{
			var firstRowIndex:int = getRowIndexByPosition( position );
			var curPage:int = getPageByRowIndex( firstRowIndex );
			if( curPage >= pageCount ) // 有可能滚动位置超出，需要控制页码
			{
				curPage = pageCount - 1;
			}
			var pages:Array = [];
			for( var i:int = 1 ; i <= CACHE_PAGE_COUNT ; i++ )
			{
				if( curPage - i >= 0 )
				{
					pages.push( curPage - i );
				}
			}
			pages.push( curPage );
			for( var i:int = 1 ; i <= CACHE_PAGE_COUNT ; i++ )
			{
				if( curPage + i < pageCount )
				{
					pages.push( curPage + i );
				}
			}
			return pages;
		}
		public function getCurrentShowingList():Array
		{
			var result:Array = [];
			for each( var arr:Array in pageDict)
			{
				result = result.concat( arr );
			}
			return result;
		}
		
		/**
		 * 最小列数
		 */		
		public static const MIN_COLUMN_COUNT:int = 4;
		/**
		 * 每页多少行 
		 */		
		public static const ROW_COUNT_PERPAGE:int = 3;
		/**
		 * 上下缓存的页数 
		 */		
		public static const SCROLLBAR_WIDTH:int = 20;
		public static const CACHE_PAGE_COUNT:int = 1;
		public static const OVER_WIDTH:Number = 40;
		private var columnWidth:int = 230;
		private var rowHeight:int = 288;
		private var verticalGap:int = 10;
		private var horizontalGap:int = 0;
		private var paddingTop:int = 0;
		private var paddingLeft:int = 20;
		private var paddingRight:int = 20;
		private var paddingBottom:int = 5;
		private var totalRowCount:int = 0;
		public var columnCount:int = MIN_COLUMN_COUNT;
		private var spacer:Spacer;
//		private var rowLabel:CurrentRowLabel;
		// 由于推荐等造成的超出的单元格数量
		private var overCount:int = 0;
		/**
		 * 当前显示列表失效 
		 */		
		private var currentContentDirty:Boolean = false;
		/**
		 * 当前布局失效 
		 */		
		private var currentLayoutDirty:Boolean = false;
		/**
		 *  数据缓存，键为页码，值为对应该页的一个数组，数组元素为数据项
		 */	
		private var pageDict:Dictionary = new Dictionary();
		/**
		 *  当前显示的renderer的缓存，键为页码，值为对应该页的一个数组，数组元素为renderer
		 */		
		private var currentShowPageDict:Dictionary = new Dictionary();
		/**
		 * 缓存类 
		 */		
		private var itemCache:ItemCache = new ItemCache();
		
		private var _totalCount:int = 0;
		/**
		 * 全部数量 
		 */		
		public function get totalCount():int
		{
			return _totalCount;
		}
		public function set totalCount(value:int):void
		{
			_totalCount = value;
			invalidateCurrentContent();
		}
		/**
		 * 每页有多少个 
		 */		
		public var pageSize:int = columnCount * ROW_COUNT_PERPAGE;
		/**
		 * 总页数 
		 */		
		private var pageCount:int = 0;
		
		private var pageHaveRequestList:Array  = [];
		public function setHaveResultOfPage( p:int ):void
		{
			pageHaveRequestList[ p ] = true;
		}
		
		/**
		 * 显示某一页的数据
		 */		
		private function showPage( page:int ):void
		{
			if( pageDict[ page ] != null )
			{
				var start:Number = getTimer();
				var arr:Array = pageDict[ page ] as Array;
				var rendererArr:Array = [];
				for each( var data:Object in arr )
				{
					rendererArr.push( addItemByData( data ) );
				}
				currentShowPageDict[ page ] = rendererArr;
				var end:Number = getTimer();
//				trace( "更新第" + page + "页使用时间：：" + ( end - start ) + " ms");
			}
		}
		/**
		 * 缓存某一页的数据
		 */		
		public function addDataPage( page:int , arr:Array ):void
		{
			pageDict[ page ] = arr;
			invalidateCurrentContent();
		}
		/**
		 * 标记当前的显示内容失效，在生命周期的commitProperties方法中会更新显示列表
		 */		
		private function invalidateCurrentContent():void
		{
			currentContentDirty = true;
			invalidateProperties();
		}
		/**
		 * 将renderer添加到现实列表中
		 */		
		private function addItemByData( data:Object ):ProductItemRenderer
		{
			var itemRenderer:ProductItemRenderer = itemCache.getItem();
			itemRenderer.productItem = data as ProductItemVO;
			if( itemRenderer.parent == this )
			{
				//				itemRenderer.visible = true;
				//				itemRenderer.includeInLayout = true;
			}
			else
			{
				addChild( itemRenderer );
			}
			return itemRenderer;
		}
		/**
		 * 将renderer从显示列表删除，放到缓存，数据仍保留在缓存
		 */		
		private function removeItem( item:ProductItemRenderer ):void
		{
			if( item.parent == this )
			{
				//				item.move( 0 , 0 );
				item.visible = false;
				item.includeInLayout = false;
			}
			itemCache.addItem( item );
		}
		/**
		 * 将一页的renderer从显示列表删除 ,但数据仍然保存，待翻到该页的时候使用
		 */		
		private function removePage( page:int ):void
		{
			var rendererArray:Array = currentShowPageDict[ page ] as Array;
			if( rendererArray != null )
			{
				for( var i:int = 0 ; i < rendererArray.length ; i++ )
				{
					var renderer:ProductItemRenderer = rendererArray[ i ] as ProductItemRenderer;
					removeItem( renderer );
				}
				delete currentShowPageDict[ page ];
			}
		}
		
		protected override function commitProperties():void
		{
			super.commitProperties();
			if( width > 0 )
			{
				commitPageInfo( this.width );
				commitMaxScrollPosition();
			}
			if( cacheDirty )
			{
				commitCache();
				cacheDirty = false;
			}
			if( currentContentDirty )
			{
				commitCurrentContent();
				currentContentDirty = false;
				invalidateLayout();
			}
		}
		private function invalidateLayout():void
		{
			currentLayoutDirty = true;
			invalidateDisplayList();
		}
		
		protected override function measure():void
		{
			super.measure();
			measuredMinWidth = MIN_COLUMN_COUNT * columnWidth  +  paddingLeft + paddingRight + SCROLLBAR_WIDTH;
			measuredWidth = measuredMinWidth;
			//			measuredMinHeight = paddingTop + paddingBottom + 2 * ( rowHeight + verticalGap ) - verticalGap;
			//			measuredHeight = measuredMinHeight;
		}
		protected override function createChildren():void
		{
			super.createChildren();
			spacer = new Spacer();
			addChild( spacer );
//			rowLabel = new CurrentRowLabel();
//			rowLabel.visible = false;
//			addChild( rowLabel );
		}
		
		private function layoutRowLabel( position:int , time:Number = 0 ):void
		{
			var currentRowIndex:int = getRowIndexByPosition( position );
			MainModelLocator.getInstance().rowLabelText = ( currentRowIndex + 1 ) + "/" + totalRowCount;
//			rowLabel.text = ( currentRowIndex + 1 ) + "/" + totalRowCount;
//			rowLabel.visible = true;
//			this.setChildIndex( rowLabel , numChildren - 1 );
//			var xPosition:Number = width - SCROLLBAR_WIDTH - rowLabel.width;
//			// 用height 减去一个数量，目的是去掉箭头按钮的比重
//			var yPosition:Number = position + rowLabel.height + ( height - 30 ) * position / ( maxVerticalScrollPosition + height )  ;
//			yPosition = yPosition;
//			Tweener.addTween( rowLabel,{y:yPosition,x:xPosition,time:time,transition:"easeOutQuint"} );
			
			//			trace("position:" + position + " text:" + rowLabel.text  + " max:" + maxVerticalScrollPosition );
		}
		
		protected override function updateDisplayList(w:Number, h:Number):void
		{
			super.updateDisplayList( w , h );
			if(this.verticalScrollBar && this.verticalScrollBar.mx_internal::scrollThumb){
				this.verticalScrollBar.mx_internal::scrollThumb.minHeight = 100;
			}
			if( currentLayoutDirty )
			{
				//				trace("更新显示列表");
				layout();
//				layoutRowLabel( verticalScrollPosition  );
				currentLayoutDirty = false;
			}
			//			trace( "孩子数量：:" + this.numChildren );
		}
		/**
		 * 布局
		 */		
		private function layout():void
		{
			var start:Number = getTimer();
			var pages:Array = getNeedShowPages( verticalScrollPosition );
			for( var i:int = 0 ; i < pages.length ; i++ )
			{
				layoutItems( pages[i] )
			}
			var end:Number = getTimer();
			//			trace( "布局使用时间::" + ( end - start ) + " ms");
		}
		
		private function removeLayoutItem():void
		{
			if( layoutItem && layoutItem.parent == this  )
			{
				removeChild( layoutItem );	
			}
		}
		private var layoutItem:UIComponent;
		private var outItemPositionDict:Dictionary = new Dictionary();
		public function layoutOutItem( item:UIComponent , rowIndex:int = 0 , columnIndex:int = 1 , rowSize:int = 2 , columnSize:int = 2 ):void
		{
			layoutItem = item;
			if( item.parent != this )
			{
				addChild( item );
			}
			layoutRenderer( item , rowIndex , columnIndex );
			for( var i:int = rowIndex ; i < rowIndex + rowSize ; i ++ )
			{
				for( var j:int = columnIndex ; j < columnIndex + columnSize ; j ++ )
				{
					positionDict[  i + "," + j ] = "-1:-1";
					outItemPositionDict[ i + "," + j ] = "-1:-1";
				}
			}
		}
		
		/**
		 * 键为页码，值为字典，值字典的键为索引，值为rowIndex + "," + columnIndex 
		 */		
		private var overDict:Dictionary = new Dictionary();
		
		/**
		 * 布局某一页
		 */		
		private function layoutItems( page:int ):void
		{
			if( page < 0 ) return;
			//			trace("布局第" + page + "页");
			var rendererArray:Array = currentShowPageDict[ page ] as Array;
			if( rendererArray != null )
			{
				var startRowIndex:int = page * ROW_COUNT_PERPAGE;
				for( var i:int = 0 ; i < rendererArray.length ; i++ )
				{
					var renderer:ProductItemRenderer = rendererArray[ i ] as ProductItemRenderer;
					var columnIndex:int;
					var rowIndex:int;
					if( overDict[ page ] != null && (overDict[ page ] as Dictionary)[i] != null )
					{
						var str:String = String( (overDict[ page ] as Dictionary)[i] );
						rowIndex = str.split(",")[0];
						columnIndex = str.split(",")[1];
					}
					else
					{
						columnIndex = i % columnCount;
						rowIndex = startRowIndex + Math.floor( i / columnCount );
					}
					
					while( positionDict[ rowIndex + "," + columnIndex] != null && 
						positionDict[ rowIndex + "," + columnIndex] != ( page + ":" + i )  )
					{
						if( columnIndex == columnCount - 1 )
						{
							rowIndex++;
							columnIndex = 0;
						}
						else
						{
							columnIndex ++;
						}
					}
					if(renderer.isRecommend)
					{
						var count:int = 1;
						while( ( columnIndex == columnCount - 1 ) 
							|| ( positionDict[ rowIndex+ "," + ( columnIndex + 1 ) ] != null && positionDict[ rowIndex+ "," + ( columnIndex + 1 ) ]  != ( page + ":" + i ) )  
							|| ( positionDict[ rowIndex+ "," + columnIndex  ] != null && positionDict[ rowIndex+ "," + columnIndex ]  != ( page + ":" + i ) )
						)
						{
							overDict[ page ] ||= new Dictionary();
							(overDict[ page ] as Dictionary)[i + count] = rowIndex + "," + columnIndex;
							if( columnIndex == columnCount - 1 )
							{
								rowIndex++;
								columnIndex = 0;
							}
							else
							{
								columnIndex ++;
							}
							count++;
						}
						positionDict[ rowIndex + "," + columnIndex] = ( page + ":" + i );
						positionDict[ ( rowIndex + 1 ) + "," + columnIndex] = ( page + ":" + i );
						positionDict[ ( rowIndex + 1 ) + "," + ( columnIndex + 1 ) ] = ( page + ":" + i );
						positionDict[ rowIndex+ "," + ( columnIndex + 1 ) ] = ( page + ":" + i );
						renderer.isLastInColumn = false;
					}
					else
					{
						renderer.isLastInColumn = ( columnIndex == columnCount - 1 );
						positionDict[ rowIndex + "," + columnIndex] = ( page + ":" + i );
					}
					layoutRenderer( renderer , rowIndex , columnIndex );
				}
			}
		} 
		
		private function layoutRenderer( renderer:UIComponent , rowIndex:int , columnIndex:int ):void
		{
			var x:int = paddingLeft + columnIndex * ( columnWidth + horizontalGap ) - ( columnIndex == columnCount - 1 ? 60 : 0 );
			var y:int = paddingTop + rowIndex * ( rowHeight + verticalGap );
			renderer.visible = true;
			renderer.move( x , y );
		}
		
		
		private var positionDict:Dictionary = new Dictionary();
		private var maxPosition:int;
		/**
		 * 处理滚动条
		 */		
		private function commitMaxScrollPosition():void
		{
			maxPosition = paddingTop +  paddingBottom + ( totalRowCount + 1 ) * ( rowHeight + verticalGap ) -  verticalGap;
			spacer.move( 0 , maxPosition );
			if( this.verticalScrollBar )
			{
				this.verticalScrollBar.addEventListener( MouseEvent.MOUSE_UP , vScrollBarUpHandler );
			}
			//			trace("y:" + maxPosition + "sp:" + maxVerticalScrollPosition + " height:" + height );
		}
		
		private function vScrollBarUpHandler( e:MouseEvent ):void
		{
			fixScrollPos();
		}
		/**
		 * 根据宽度计算有多少列，每页多少条数据，总行数，总页数等分页信息
		 */		
		private function commitPageInfo( w:int ):void
		{
			var contentWidth:Number =  w - paddingLeft - SCROLLBAR_WIDTH - OVER_WIDTH;
			var newColumnCount:int =  Math.floor( contentWidth / columnWidth  );
			if( columnCount != newColumnCount )
			{
				columnCount = newColumnCount;
				invalidateLayout();
			}
			pageSize = columnCount * ROW_COUNT_PERPAGE;
			totalRowCount = Math.ceil( (totalCount + overCount) /  columnCount );
			pageCount = Math.ceil( ( totalCount + overCount) / pageSize );
			// 这里加60像素是为了调整每一列最后一个的布局，让图片看起来是平均的
			horizontalGap = ( contentWidth - columnCount * columnWidth + 60 ) / (columnCount - 1);
			layoutRowLabel( this.verticalScrollPosition );
			//			trace("horizontalGap::" + horizontalGap );
		}
		
		private function commitCache():void
		{
			var lastPage:int = 0;
			var arr:Array = [];
			var newPageDict:Dictionary = new Dictionary();
			for ( var pageIndex:String in pageDict )
			{
				if( int(pageIndex) - lastPage > 1 )
				{
					break; // 不是连续的则舍弃后面的部分
				}
				var pageData:Array = pageDict[ pageIndex ] as Array;
				arr = arr.concat( pageData );
				lastPage = int(pageIndex);
			}
			// 合并所有已有的数据
			// 重新划分
			arr = arr.reverse();
			var pageCount:int = Math.floor( arr.length / pageSize );
			for( var i:int = 0 ; i < pageCount ; i++ )
			{
				var newPageArr:Array = [];
				for( var j:int = 0 ; j < pageSize ; j++ )
				{
					newPageArr.push( arr.pop() );
				}
				newPageDict[ i ] = newPageArr;
			}
			pageDict = newPageDict;
		}
	}
}